#!/bin/bash

function usage() {
    echo "Usage: $0 [output_dir]"
    echo "Export all images from k8s.io namespace to output_dir"
    echo "If no output_dir is provided, will export to current dir's subdir images"
    exit 1
}

# waring this operation will clear target dir
if [ "$#" -gt 1 ]; then
    usage
fi

# show warning and waiting user input
echo "This operation will clear target dir, please confirm to continue"
read -p "Press enter to continue or Ctrl+C to cancel"

# check if ctr is installed
if ! command -v ctr &> /dev/null
then
    echo "ctr is not installed. Please install ctr and try again."
    exit 1
fi


# from args then default to current dir's subdir images
OUTPUT_DIR=$1

if [ -z "$OUTPUT_DIR" ]; then
    OUTPUT_DIR="./images"
    mkdir -p $OUTPUT_DIR
fi

# check if output dir exists
if [ ! -d "$OUTPUT_DIR" ]; then
    echo "$OUTPUT_DIR  Output directory does not exist. Please create it and try again."
    exit 1
fi

# check if output dir is writable
if [ ! -w "$OUTPUT_DIR" ]; then
    echo "Output directory is not writable. Please check permissions and try again."
    exit 1
fi
rm -rf $OUTPUT_DIR/*


IMAGES=$(ctr -n k8s.io i ls -q | grep -v sha256 | grep -v hub.cangling.cn | grep -v workflow)

for image in $IMAGES; do
    echo "Exporting image: $image"
    # extract image name
    image_name=$(echo $image |  cut -d '/' -f 3 | cut -d ':' -f 1)
    # export to format .tar.gz
    ctr -n k8s.io i export    $OUTPUT_DIR/${image_name}.tar "$image"
done

echo "Images exported to $OUTPUT_DIR total count: $(ls $OUTPUT_DIR | wc -l)"